package EventLoopTest.Test001;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class NettyTimeClient {
    
    private final String host;
    private final int port;
    
    public NettyTimeClient(String host, int port) {
        this.host = host;
        this.port = port;
    }
    
    public void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                     .channel(NioSocketChannel.class)
                     .handler(new ChannelInitializer<SocketChannel>() {
                         @Override
                         protected void initChannel(SocketChannel ch) {
                             ChannelPipeline pipeline = ch.pipeline();
                             pipeline.addLast(new LineBasedFrameDecoder(1024));
                             pipeline.addLast(new StringDecoder(StandardCharsets.UTF_8));
                             pipeline.addLast(new StringEncoder(StandardCharsets.UTF_8));
                             pipeline.addLast(new TimeClientHandler());
                         }
                     });
            
            // 连接服务器
            Channel channel = bootstrap.connect(host, port).sync().channel();
            System.out.println("连接服务器成功，请输入命令 (time/timestamp/quit):");
            
            // 读取用户输入
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                if ("quit".equalsIgnoreCase(line)) {
                    channel.writeAndFlush(line).addListener(ChannelFutureListener.CLOSE);
                    break;
                }
                channel.writeAndFlush(line + "\n");
            }
            
            // 等待连接关闭
            channel.closeFuture().sync();
            
        } finally {
            group.shutdownGracefully();
        }
    }
    
    private static class TimeClientHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            String response = (String) msg;
            System.out.println("服务器响应: " + response);
        }
        
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            cause.printStackTrace();
            ctx.close();
        }
    }
    
    public static void main(String[] args) throws Exception {
        new NettyTimeClient("localhost", 8888).run();
    }
}